/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
define(["common"],function($){
  if($.shopApp){
    console.log("返回唯一应用对象.")
    return $.shopApp;
  }
  
  var app = {
      /*
       * 逻辑视图设置
       */
      logicView:{
        width:-1,
        height:1
      },
      /*
       * 放大缩小后实际视图大小.
       * 比如:物理大小10*10，
       * 逻辑大小：100*100，
       * 整个页面有：0.5，0.5缩放
       * 实际页面大小是200*200
       */
      realView:{
        width:-1,
        height:1
      },
      /*
       * html元素
       */
      physicalView:{
        width:1,
        height:1
      },
      
      
      events:[],//应用两帧之间发生的事件
      callbacks:[],//事件处理后需要执行的回调函数
      scale:1,//缩放比例
      setLogicViewWidth:function(width){this.logicView.width=width;},
      setLogicViewHeight:function(height){this.logicView.height=height;},
      setRealViewWidth:function(width){this.realView.width=width;},
      setRealViewHeight:function(height){this.realView.height=height;},
      setPhysicalViewWidth:function(width){this.physicalView.width=width;},
      setPhysicalViewHeight:function(height){this.physicalView.height=height;},
      getLogicViewWidth:function(){return this.logicView.width;},
      getLogicViewHeight:function(){return this.logicView.height;},
      getRealViewWidth:function(){return this.realView.width;},
      getRealViewHeight:function(){return this.realView.height;},
      getPhysicalViewWidth:function(){return this.physicalView.width;},
      getPhysicalViewHeight:function(){return this.physicalView.height;},
      
      
      /**
       * 添加事件
       * @param ev
       */
      addEvent:function(ev){
        if(this.events){
          this.events[this.events.length]=ev;
        }
        //console.log(this.events);
      },
      /**
       * 添加回调函数.
       * <p>两帧之间执行的回调函数.</p>
       * @param fn 要执行的回调函数.
       */
      addCallback:function(fn){
        this.callbacks[this.callbacks.length]=fn;
      },
      /**
       * 获得上一帧第一个发生的指定类型的事件.
       * @param eventName 事件名称
       * @returns 
       */
      findEvent:function(eventName){
        for(idx in this.activeEvents){
          var cur = app.activeEvents[idx];
          if(eventName&&cur&&eventName==cur.reason){
            return cur;
          }
        }
        return null;
      },
      findEvents:function(eventName){
        var res = [];
        for(idx in this.activeEvents){
          var cur = app.activeEvents[idx];
          if(eventName&&cur&&eventName==cur.reason){
            res.push(cur);
          }
        }
        return res;
      },
      findBizClick:function(){
        //console.log(JSON.stringify(this.events))
        var res = this.findEvent("click");
        res = (res?res:this.findEvent("tap"));
        return res;
      },
      // Application Constructor
      initialize: function() {
          this.bindEvents();
      },
      // Bind Event Listeners
      //
      // Bind any events that are required on startup. Common events are:
      // 'load', 'deviceready', 'offline', and 'online'.
      bindEvents: function() {
          //document.addEventListener('deviceready', this.onDeviceReady, false);
        //$(document).on('deviceready',this.onDeviceReady);
      },
      // deviceready Event Handler
      //
      // The scope of 'this' is the event. In order to call the 'receivedEvent'
      // function, we must explicitly call 'app.receivedEvent(...);'
      onDeviceReady: function(ev) {
        app.receivedEvent('deviceready',bizObj);
      }
      ,
      // Update DOM on a Received Event
      receivedEvent: function(id) {
        if(id=='deviceready'){
          $(function(){
            function display(time){
              app.activeEvents=app.events;
              app.events=[];
              app.callbacks=[];
              $("body").trigger("display",$.extend({},app.events,{time:time}));
              //调用事件处理的callback函数
              app.callbacks.reverse();
              for(idx in app.callbacks){
                var fn = app.callbacks[idx];
                if(!fn._is_invoked){
                  fn._is_invoked=true;
                  if(false==fn.call(window,fn.event)){
                    break;
                  }
                }
              }
              window.requestNextAnimationFrame(display);
            }
            window.requestNextAnimationFrame(display);
          });
        }
        
      }
  };
  
  window.addEventListener('load', function() {
    FastClick.attach(document.body);
  }, false);

  app.initialize();
  
  
  $(function(){
    app.receivedEvent('deviceready');
  });
  
  window.app=app;
  $.shopApp=app;
  return app;
})

